package com.egoo.ticket.server.exception;

import com.egoo.ticket.server.utils.common.DbResponse;
import com.egoo.ticket.server.utils.common.ResponseConstant;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.Objects;

/**
 * @Author: Donny_dong
 * @Description: 全局异常处理
 * @Param:
 * @return:
 * @Date: 2021/1/12
 */
@RestControllerAdvice
@Log4j2
public class GlobleExceptionHandle extends ResponseEntityExceptionHandler {

	@ExceptionHandler(Exception.class)
	public DbResponse handleException(Throwable e){
		if (Objects.isNull(e)){
			return null;
		}
		log.info("异常信息："+e.getMessage()+"---异常栈："+e.getStackTrace());
		return new DbResponse(ResponseConstant.RES_FAIL_CODE,"系统异常");
	}

	@Override
	protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
		//这里将异常直接传给handlerException()方法进行处理，返回值为OK保证友好的返回，而不是出现500错误码。
		return new ResponseEntity<>(handleException(ex), HttpStatus.OK);
	}

}
